class ContextsController < ApplicationController
  # GET /contexts
  # GET /contexts.xml
  def index
    @contexts = @context_elements
    
    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @contexts.to_xml }
    end
  end
  
  # GET /contexts/1
  # GET /contexts/1.xml
  def show
    @context = Context.find(params[:id])
    
    respond_to do |format|
      format.html # show.rhtml
      format.xml  { render :xml => @context.to_xml }
    end
  end
  
  def permalink
    Context.destroy_all(session_user, @context_elements)
    params[:context].each do |c|
      context = Context.new(:artifact_id => c,:user_id => @session_user) 
      context.save!
    end
    redirect_to :controller=>'artifacts',:action=>'index',:id=>nil
  end
  
  # GET /contexts/new
  def new
    @context = Context.new
  end
  
  # GET /contexts/1;edit
  def edit
    @context = Context.find(params[:id])
  end
  
  # POST /contexts
  # POST /contexts.xml
  def create
    @context = Context.new(params[:context])
    
    respond_to do |format|
      if @context.save
        flash[:notice] = 'Context was successfully created.'
        format.html { redirect_to context_url(@context) }
        format.xml  { head :created, :location => context_url(@context) }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @context.errors.to_xml }
      end
    end
  end
  
  # PUT /contexts/1
  # PUT /contexts/1.xml
  def update
    @context = Context.find(params[:id])
    
    respond_to do |format|
      if @context.update_attributes(params[:context])
        flash[:notice] = 'Context was successfully updated.'
        format.html { redirect_to context_url(@context) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @context.errors.to_xml }
      end
    end
  end
  
  def destroy_all
    Context.destroy_all(session_user, @context_elements)
    @context_elements = session_user.contexts
    @artifacts = Artifact.get_artifacts(@session_user, @context_elements)
    render :action => 'update_panes', :type=>'rjs' and return true
  end
  
  # DELETE /contexts/1
  # DELETE /contexts/1.xml
  def destroy
    @context = Context.find(params[:id])
    Recent.add(@context.artifact, @session_user)
    @context.destroy
    
    @context_elements = session_user.contexts
    
    @artifacts = Artifact.get_artifacts(@session_user, @context_elements)
    
    if request.xhr?
      render :action => 'update_panes', :type=>'rjs' and return true 
    end 
    
    respond_to do |format|
      format.html { redirect_to contexts_url }
      format.xhtml { render :template => 'artifacts/index.rxhtml', :layout=>false }
      format.xml  { head :ok }
    end
  end
end
